<?php

namespace app\common\service;
use think\Filesystem;
use think\file\UploadedFile;

class UploadService
{
    /**
     * @var Filesystem
     */
    protected $fileSystem;

    /**
     * 图片保存路径
     * @var string
     */
    protected $imagePath = 'upload/images';

    /**
     * 文件保存路径
     * @var string
     */
    protected $filePath = 'upload/files';

    /**
     * 初始化
     */
    public function __construct(Filesystem $filesystem)
    {
        $this->fileSystem = $filesystem;
    }

    /**
     * 图片上传
     * @param array $params
     * @return array
     */
    public function image(array $params)
    {
        return $this->returnPath($this->imagePath, $params['file']);
    }

    /**
     * 文件上传
     * @param array $params
     * @return array
     */
    public function file(array $params)
    {
        return $this->returnPath($this->filePath, $params['file']);
    }

    /**
     * 编辑器图片上传
     * @param array $params
     * @return array
     */
    public function tinymce(array $params)
    {
        $uploadRst = $this->returnPath($this->filePath, $params['edit']);
        $uploadRst['data'] = $uploadRst['data']['url'];
        return $uploadRst;
    }

    /**
     * 上传处理
     * @param string $filePath
     * @param UploadedFile $file
     * @return array
     */
    protected function returnPath(string $filePath, UploadedFile $file)
    {
        $upFile = $this->fileSystem->disk('file')->putFile($filePath, $file);
        // 自动添加扩展名称
        if (empty(explode('.', $upFile)[1]) && in_array($file->getOriginalMime(), ['image/png'])) {
            rename($upFile, $upFile . 'png') && $upFile .= 'png';
        }
        return ['msg' => '上传成功', 'data' => ['path' => $upFile, 'url' => realImgUrl($upFile), 'fileName' => $file->getOriginalName()]];
    }
}